package com.qinke.testxml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomParser {
	public static List<Map<String,String>> read(String uri,String nodeName){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document d = builder.parse(uri);
			
			Element root = d.getDocumentElement();
			
			NodeList nodelist = root.getChildNodes();
			
			for(int i = 0; i<nodelist.getLength();i++){
				Node node =  nodelist.item(i);
				if(!nodeName.equals(node.getNodeName())){
					continue;
				}
				Map<String,String> map = new HashMap<String,String>();
				String id =node.getAttributes().getNamedItem("id").getNodeValue();
				map.put("id", id);
				
				for(Node child = node.getFirstChild();child!=null;child = child.getNextSibling()){
					if(child.getNodeType() == Node.ELEMENT_NODE){
						if("name".equals(child.getNodeName()))
							map.put("name", child.getFirstChild().getNodeValue());
						else if("age".equals(child.getNodeName()))
							map.put("age", child.getFirstChild().getNodeValue());
						else if("gender".equals(child.getNodeName()))
							map.put("gender", child.getFirstChild().getNodeValue());
					}
						
				}
				list.add(map);
				map = null;
			}
		} catch (SAXException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
